package com.fauks.gmall.user.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.fauks.gmall.bean.UmsMember;
import com.fauks.gmall.bean.UmsMemberReceiveAddress;
import com.fauks.gmall.service.UserService;
import com.fauks.gmall.user.mapper.UserMapper;
import com.fauks.gmall.user.mapper.UmsMemberReceiveAddressMapper;
import com.fauks.gmall.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper memberMapper;

    @Autowired
    private UmsMemberReceiveAddressMapper umsMemberReceiveAddressMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public List<UmsMember> getAllMember() {
        return memberMapper.selectAll();
    }

    @Override
    public List<UmsMemberReceiveAddress> getReceiveAddressByMemberId(String memberId) {
        Example example = new Example(UmsMemberReceiveAddress.class);
        example.createCriteria().andEqualTo("memberId", memberId);
        return umsMemberReceiveAddressMapper.selectByExample(example);
    }

    @Override
    public UmsMember login(UmsMember umsMember) {

        Jedis jedis = null;
        try {
            jedis = redisUtils.getJedis();
            String key = "user:" + umsMember.getPassword() + "info";
            if (jedis != null) {
                String userInfoStr = jedis.get(key);
                if (!StringUtils.isEmpty(userInfoStr)) {
                    return JSON.parseObject(userInfoStr, UmsMember.class);
                }
            }
            //redis连接失败、redis不存在用户缓存，需要从DB获取
            UmsMember memberFromDB = memberMapper.selectOne(umsMember);
            if (memberFromDB != null && jedis != null) {
                jedis.setex(key, 60 * 60 * 24, JSON.toJSONString(memberFromDB));
            }
            return memberFromDB;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    @Override
    public void addUserToken(String token, String id) {
        Jedis jedis = redisUtils.getJedis();
        jedis.setex("user:" + id + ":token", 60 * 60 * 24, token);
        jedis.close();
    }
}
